import { Injectable, ForbiddenException } from '@nestjs/common';
import { CreateDepartmentDto } from './dto/create-department.dto';
import { UpdateDepartmentDto } from './dto/update-department.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Department } from './entities/department.entity';

@Injectable()
export class DepartmentService {
  constructor(
    @InjectRepository(Department)
    private departmentRepository: Repository<Department>,
  ) {}

  // 创建学院
  async create(createDepartmentDto: CreateDepartmentDto) {
    const res = await this.departmentRepository.create(createDepartmentDto);
    return await this.departmentRepository.save(res);
  }

  // 查找所有学院
  findAll() {
    return this.departmentRepository.find();
  }

  // 学院详情
  findOne(id: number) {
    return this.departmentRepository.findOne({
      where: { id },
    });
  }

  async findSubordinate(id: number) {
    const res = await this.departmentRepository
      .createQueryBuilder('department')
      .where({ id })
      .leftJoinAndSelect('department.major', 'major')
      .where('department.id = :id', { id })
      .getOne();
    return res;
  }

  // 更新学院
  async update(id: number, updateDepartmentDto: UpdateDepartmentDto) {
    const findRes = await this.findOne(id);
    if (!findRes?.id) {
      throw new ForbiddenException('学院不存在');
    }
    const newDto = this.departmentRepository.merge(
      findRes,
      updateDepartmentDto,
    );
    return this.departmentRepository.save(newDto);
  }

  // 删除学院
  async remove(id: number) {
    const res = await this.findOne(id);
    if (res?.id) {
      return await this.departmentRepository.remove(res);
    }
    throw new ForbiddenException('学院不存在');
  }
}
